# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os
import Cookie
import time

from django.utils import simplejson

from settings import DEFAULT_UNITS
from middleware import cc_cookies

COOKIE_NAME = 'magicycles-units'
UNITS_DISTANCE = ("metric", "imperial",)
KM2MILE = 0.621371192
MILE2KM = 1 / KM2MILE
M2FT = 3.2808399
FT2M = 1 / M2FT

def get_current_units():
    browser_cookie = os.environ.get('HTTP_COOKIE', '')
    cookie = Cookie.SimpleCookie()
    cookie.load(browser_cookie)
    try:
        units = simplejson.loads(cookie[COOKIE_NAME].value)
    except Exception:
        units = DEFAULT_UNITS
        save_current_units(units)
    return units


def save_current_units(units):
    if not isinstance(units, unicode):
        units = unicode(units, 'utf-8')
    if units not in UNITS_DISTANCE:
        units = DEFAULT_UNITS

    cookie = Cookie.SimpleCookie()
    now = time.asctime()
    cookie[COOKIE_NAME] = simplejson.dumps(units)
    cookie[COOKIE_NAME]['expires'] = now[:-4] + str(int(now[-4:]) + 1) + ' GMT'
    cookie[COOKIE_NAME]['path'] = '/'
    #print cookie
    cc_cookies.add_cookie(cookie)

converter = {
    "metric": lambda x: x,
    "imperial": lambda x: x * KM2MILE
}
KM_Mile = {
    "metric": "km",
    "imperial": "miles"
}
M_Feet = {
    "metric": "m",
    "imperial": "feet"
}

def convert(distance):
    return converter[get_current_units()](distance)

_c = convert

def main():
    pass

if __name__ == '__main__':
    main()
